package com.DataFactory.user.controller;

import com.DataFactory.user.common.Result;
import com.DataFactory.user.common.ResultCodeEnum;
import com.DataFactory.user.entity.File;
import com.DataFactory.user.model.SignFileEntity;
import com.DataFactory.user.service.FileUploadService;
import com.DataFactory.user.utils.Utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class FileUploadController {
    @Autowired
    private FileUploadService fileUploadService ;
    @Autowired
    private RestTemplate restTemplate;
    @PostMapping(value = "/fileUpload")
    public Result<String> fileUploadService(@RequestParam(value = "file") MultipartFile multipartFile,
                                            @RequestParam(value = "privateKey") String privateKey,
                                            @RequestParam(value = "id") String id,
                                            @RequestParam(value = "receiver") String receiver) throws IOException {
// 创建 MultiValueMap 来存储请求参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("file", new ByteArrayResource(multipartFile.getBytes()) {
            @Override
            public String getFilename() {
                return multipartFile.getOriginalFilename();
            }
        });
        params.add("privateKey", privateKey);

// 创建 HttpHeaders 并设置内容类型为 multipart/form-data
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

// 创建 HttpEntity 并添加请求参数
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);

// 发送 POST 请求
        String url = "http://127.0.0.1:8082/sign/signature";
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        ObjectMapper objectMapper = new ObjectMapper();

// 将 JSON 字符串解析为 Map 类型，以便提取 data 字段
        Map<String, Object> jsonResponse = objectMapper.readValue(responseEntity.getBody(), new TypeReference<Map<String, Object>>() {});

// 从解析后的 Map 中提取 data 字段
        String data = (String) jsonResponse.get("data");
        // 获取文件的字节数组
        System.out.println(data);
//        multipartFile.getBytes();
        SignFileEntity signFileEntity = new SignFileEntity();
        signFileEntity.setSender(id);
        signFileEntity.setReceiver(receiver);
        signFileEntity.setSignature(data);
        String fileUrl = fileUploadService.fileUpload(multipartFile,signFileEntity);
        return Result.build(fileUrl , ResultCodeEnum.SUCCESS);
//        return null;
    }

    @GetMapping("/fileDownload/{pubKey}")
    public Result<String> fileDownload(
            @PathVariable String pubKey
    ) throws JsonProcessingException {
        File file = fileUploadService.download(pubKey);

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("url",file.getUrl());
        params.add("pubKey",file.getSender());
        params.add("signature",file.getSignature());
// 创建 HttpHeaders 并设置内容类型为 multipart/form-data
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

// 创建 HttpEntity 并添加请求参数
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);

        String url = "http://127.0.0.1:8082/sign/verify";
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,entity, String.class);
        ObjectMapper objectMapper = new ObjectMapper();

// 将 JSON 字符串解析为 Map 类型，以便提取 data 字段
        Map<String, Object> jsonResponse = objectMapper.readValue(responseEntity.getBody(), new TypeReference<Map<String, Object>>() {});
// 从解析后的 Map 中提取 data 字段
        Boolean result = (Boolean) jsonResponse.get("data");

        if(result){
            return Result.build(file.getUrl(),ResultCodeEnum.SUCCESS);
        }
        return Result.build(null,ResultCodeEnum.DATA_ERROR);
    }
}